import React from 'react'
import {connect} from 'react-redux'
import { Row, Col, Timeline, message, Spin, Button, DatePicker, Modal } from 'antd';
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common";
import 'styles/loan-billing/view-line.scss'
import moment from "moment/moment";
import borrowService from "containers/loan-billing/borrow-and-return.service";
import menuRoute from "routes/menuRoute";
import TextArea from 'antd/lib/input/TextArea';
const TimelineItem = Timeline.Item;
const { confirm } = Modal;
class ExtendLoad extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      recordInfo: {},
      loading: false,
      contractInfo: {},
      mode: '',
      delayDate: '',
      businessCode: '',
      buttonLoading: false,
      loanDetail: menuRoute.getRouteItem('line-loan-detail'),
    }
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.extendMoneyFrame === this.props.extendMoneyFrame){
      return -1;
    }
    if(!nextProps.extendMoneyFrame){
      this.setState({recordInfo: {}});
      return -1;
    }
    this.setState({loading: true});
    Promise.all([
      borrowService.getLineInfo(nextProps.viewId),
      borrowService.getLineDetail(nextProps.viewId)
    ]).then(res => {
      this.setState({
        recordInfo: res[1].data,
        delayDate: res[1].data.delayDate ? moment(res[1].data.delayDate).format('YYYY-MM-DDTHH:mm:ss.SSSZ') : '',
        loading: false,
        contractInfo: res[0].data,
        mode: nextProps.mode,
        businessCode: nextProps.businessCode
      });
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages('loan-billing.key25')/*系统异常*/);
    });
  }

  submit = () => {
    const { delayDate, recordInfo, mode } = this.state;
    const  { onClose } = this.props
    if (!recordInfo.remark || recordInfo.remark.length === 0) {
      message.warning('请填写延长划款原因');
      return false;
    }
    if (delayDate) {
      this.setState({ buttonLoading: true })
      if (mode === 'add') {
        console.log(delayDate)
        const params = {
          loanLineId: recordInfo.id,
          delayDate,
          delayFlag: 1,
          remark: recordInfo.remark
        };
        borrowService.handleDelayDateOrToForeverAmount(params).then(res => {
          console.log(res);
          if (res.status === 200) {
            message.success('延长还款时间成功');
            this.setState({ buttonLoading: false })
            if (onClose) {
              onClose()
            }
          } else {
            message.error(res.message);
            this.setState({ buttonLoading: false })
          }
        }).catch(err => {
          console.log(err)
          this.setState({ buttonLoading: false })
          let that = this;
          if (err.response.data.message.indexOf('删除原有单据') !== -1) {
            confirm({
              title: err.response.data.message,
              okText: '确认',
              onOk() {
                borrowService.getIngDelayToforeverLoanBill(recordInfo.id).then(data => {
                  if (data.status === 200) {
                    console.log(data)
                    that.context.router.push(that.state.loanDetail.url.replace(':formOID',data.data.formOID).replace(':loanBillOID',data.data.loanBillOID).replace(':backType','history'));
                  }
                }).catch(error => {
                  message.error(error.message);
                })
              },
              onCancel() {},
            });
          } else {
            message.error(err.response.data.message);
          }
        })
      } else {
        const params = {
          loanLineId: recordInfo.id,
          delayDate,
          remark: recordInfo.remark
        };
        borrowService.handleUpdateDelayDateOrForeverAmount(params).then(res => {
          if (res.status === 200) {
            message.success('延长还款时间成功');
            this.setState({ buttonLoading: false })
            if (onClose) {
              onClose()
            }
          } else {
            message.error(res.message);
            this.setState({ buttonLoading: false })
          }
        }).catch(err => {
          console.log(err)
          message.error(err.response.data.message);
          this.setState({ buttonLoading: false })
        })
      }
    } else {
      message.warning('请填写延长还款日期');
    }
  }

  handleOnRemarkChange = (e) => {
    const tempRecordInfo = deepFullCopy(this.state.recordInfo)
    tempRecordInfo.remark = e.target.value
    this.setState({
      recordInfo: tempRecordInfo
    })
  }

  render(){
    const { recordInfo, loading, contractInfo, mode, businessCode, buttonLoading } = this.state;
    // console.log('recordInfo', recordInfo)
    return(
      <div className='view-line'>
      <Spin spinning={loading}>
        <div className='stroke-title'><span>{messages('common.baseInfo')/*基本信息*/}</span></div>
        <div>
          <Row>
            <Col span={6}>{messages('loan-billing.key12')/*借款类型*/}：</Col>
            <Col span={17} offset={1}>{recordInfo.loanTypeName}</Col>
          </Row>
          <Row>
            <Col span={6}>{messages('loan-billing.key68')/*收款方*/}：</Col>
            <Col span={17} offset={1}>
              <span className={recordInfo.payeeType === 1002 ? 'table-blue' : 'table-grey'} style={{padding: '3px 5px', marginRight: '10px'}}>{recordInfo.payeeType === 1002 ? messages('loan-billing.key14')/*员工*/ : messages('loan-billing.key15')/*供应商*/}</span>
              {recordInfo.payeeName}
            </Col>
          </Row>
          {/* <Row>
            <Col span={6}>收款账号：</Col>
            <Col span={17} offset={1}>
              <div>账户：{recordInfo.payeeAccountNumber}</div>
              <div>户名：{recordInfo.payeeAccountName}</div>
            </Col>
          </Row> */}
          <Row>
            <Col span={6}>{messages('loan-billing.key11')/*借款金额*/}：</Col>
            <Col span={17} offset={1}>{`${recordInfo.currencyCode}  ${this.filterMoney(recordInfo.amount,queryCurrencyPrecision(recordInfo.currencyCode), true)}`}</Col>
          </Row>
          <Row>
            <Col span={6}>{messages('loan-billing.key205')/*可延长金额*/}：</Col>
            <Col span={17} offset={1}>{`${recordInfo.currencyCode}  ${this.filterMoney(recordInfo.stayWriteOffAmount,queryCurrencyPrecision(recordInfo.currencyCode), true)}`}</Col>
          </Row>
          {
            recordInfo.planedPaymentDate &&
            <Row>
              <Col span={6}>{messages('loan-billing.key109')/*计划付款日期*/}：</Col>
              <Col span={17} offset={1}>{recordInfo.planedPaymentDate ? moment(recordInfo.planedPaymentDate).format('YYYY-MM-DD') : '-'}</Col>
            </Row>
          }
          <Row>
            <Col span={6}>{messages('loan-billing.key148')/*预计还款日期*/}：</Col>
            <Col span={17} offset={1}>{recordInfo.planedRepaymentDate ? moment(recordInfo.planedRepaymentDate).format('YYYY-MM-DD') : '-'}</Col>
          </Row>

          {mode == 'add' ? <Row>
            <Col span={6}>{messages('loan-billing.key200')/*延长还款日期至*/}：</Col>
            <Col span={17} offset={1}>
              <DatePicker
                placeholder="请选择"
                disabledDate={date => ((date < moment(recordInfo.planedRepaymentDate) || date < moment().endOf('day')) || date > moment(recordInfo.submitDate).add(2, 'y'))}
                onChange={date => this.setState({
                  delayDate: moment(date).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
                })}
              />
            </Col>
          </Row> : ''}

          {mode == 'edit' ? <Row>
            <Col span={6}>{messages('loan-billing.key200')/*延长还款日期至*/}：</Col>
            <Col span={17} offset={1}>
              <DatePicker
                placeholder="请选择"
                defaultValue={moment(recordInfo.delayDate)}
                disabledDate={date => date < moment(recordInfo.delayDate).endOf('day') || date > moment(recordInfo.submitDate).add(2, 'y')}
                onChange={date => this.setState({
                  delayDate: moment(date).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
                })}
              />
            </Col>
          </Row> : ''}
          {mode == 'read' ? <Row>
            <Col span={6}>{messages('loan-billing.key198')/*延长还款日期*/}：</Col>
            <Col span={17} offset={1}>{recordInfo.delayDate ? moment(recordInfo.delayDate).format('YYYY-MM-DD') : '-'}</Col>
          </Row> : ''}
          {mode == 'read' ? <Row>
            <Col span={6}>{messages('loan-billing.key201')/*原单号*/}：</Col>
            <Col span={17} offset={1}>{recordInfo && recordInfo.oldLoanBillDTO && recordInfo.oldLoanBillDTO.businessCode}</Col>
          </Row> : ''}
          <Row>
            <Col span={6}>延长还款原因：</Col>
            <Col span={17} offset={1}>
              {
                mode === 'read' ?
                  recordInfo.remark :
                  <TextArea
                    onChange={(e) => this.handleOnRemarkChange(e)}
                    value={recordInfo.remark}
                    style={{ width: '60%', height: '100px' }}
                  />
            }</Col>
          </Row>
        </div>
       
      </Spin>
        <div className="slide-footer">
          <Button onClick={this.props.close}>{messages('common.back')/*返回*/}</Button>
          {mode !== 'read' ? <Button loading={buttonLoading} onClick={this.submit} type="primary">{messages('common.submit')/*提交*/}</Button> : ''}
        </div>
      </div>
    )
  }
}

ExtendLoad.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {

  }
}

export default connect(mapStateToProps)(ExtendLoad);
